package com.houzhiwen.util;

import com.houzhiwen.javabeam.User;
import mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class UserTest {
    SqlSession session;
    UserMapper mapper;
    @Before
    public void a() {
        //1、创建SqlSessionFactory对象，也是单例模式的
        SqlSessionFactory factory = MyBatisUtil.getSqlSessionFactory();
        //2、创建SqlSession对象 true 自动提交事务 不写也没事 因为默认在sqlsession关闭时提交事务
        session = factory.openSession(true);
        //3、调用session的方法namespace的名字.id
        mapper = session.getMapper(UserMapper.class);
    }

    @After
    public void b() {
        //5、关闭资源
        session.close();
    }

    @Test
    public void selectAll(){
        for (User user : mapper.selectAll()) {
            System.out.println(user);
        }
    }

    @Test
    public void selectUser_Role(){
        for (User user : mapper.selectUser_Role()) {
            System.out.println(user);
        }
    }

    //动态SQL的test--if,where标签
    @Test
    public void selectUser(){
        User u = new User();
        for( User user : mapper.selectUser(u)){
            System.out.println(user);
        }
    }

    //动态SQL的test--choose标签
    @Test
    public void selectUserOne(){
        User u = new User();
        u.setUid(1);
        //u.setUsername("a");
        //u.setPassword("a");
        for( User user : mapper.selectUserOne(u)){
            System.out.println(user);
        }
    }

    //动态SQL的test--set标签
    @Test
    public void updateUser(){
        User u=new User();
        u.setUid(3);
        u.setUsername("houzhiwen");
        u.setPassword("11111");
        u.setPhone("188");
        mapper.updateUser(u);
    }


    //    批量删除
    @Test
    public void deleteByArray(){
        int[] ids={5,6,7,8,9};
        mapper.deleteByArray(ids);
    }

    @Test
    public void insertList(){
        List<User> list=new ArrayList<>();
        list.add( new User("haha","111","111"));
        list.add( new User("hou","22","222"));
        list.add( new User("houhou","333","333"));
        mapper.insertList(list);
    }
}
